<?php
namespace control;

/*
*公文发文类
*/


class officialDocumentSendClass extends adIndexClass
{
    private const title = '公文发文';
    private const page = 'officialDocumentSend';
    private const table = 'official_document';
    public const workFlowOption = ['草拟中', '审核中', '已签发', '已撤销', '已废止'];
    private array $urgentLevelOption = ['平急', '加急', '特急'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'allSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'isArchive'          => [
                        'name'  => '归档状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'issuedSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'signStid'          => [
                        'name'  => '签发人',
                        'width' => 200,
                    ],
                    'signTime'          => [
                        'name'  => '签发时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'documentAuditSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'approverId'          => [
                        'name'  => '当前节点',
                        'width' => 200,
                    ],
                    'commitTime'          => [
                        'name'  => '提交审批时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'abolishedSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'abandText'          => [
                        'name'  => '废止事由',
                        'width' => 200,
                    ],
                    'abandTime'          => [
                        'name'  => '废止时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'revokeSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'revokeText'          => [
                        'name'  => '撤销事由',
                        'width' => 200,
                    ],
                    'revokeTime'          => [
                        'name'  => '撤销时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 120,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '拟制人',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '拟制时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }
    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        //生成查询表单
        $dateTitle = '创建日期';
        if ($workFlow == '草拟中') {
            $dateTitle = "拟制日期";
        } elseif ($workFlow == '审核中') {
            $dateTitle = "提交审批时间";
        } elseif ($workFlow == '已签发') {
            $dateTitle = "签发日期";
        } elseif ($workFlow == '已撤销') {
            $dateTitle = "撤销日期";
        } elseif ($workFlow == '已废止') {
            $dateTitle = "废止日期";
        }
        $array = [
            [
                [
                    "发文字号" => text(array("name" => "preText")),
                    "公文种类"     => select(array("name" => "type", "option" => explode("，", para("officialDocumentType")))),
                    "标题" => text(array("name" => "title")),
                ],
                [
                    '密级'   => select(array("name" => "secretLevel", "option" => explode('，',para('secretLevelOption')))),
                    "紧急程度" => select(array("name" => "urgentLevel", "option" => $this->urgentLevelOption)),
                    $dateTitle   => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($workFlow == '全部') {
            $array[0][] = [
                '状态'   => select(array("name" => "workFlow", "option" => self::workFlowOption)),
                "归档状态" => select(array("name" => "isArchive", "option" => ['未归档', '已归档'])),
            ];
        }
        //生成查询表单
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('草拟中');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('新建" . self::title . "','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            'workFlow' => '草拟中',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        if (!$this->power(self::page,'seeAll')){
            $and .= self::seeSelf(self::page);
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("draftForm", "draftId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "draftId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='draftForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function revokeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已撤销');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已撤销
     *
     */
    public function revoke(): bool|string
    {
        $html = $this->revokeOptions(false);
        //控件
        $button = "";
        if ($this->power('officialRevoke', "archive")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','addArchive',{formName:'revokeForm'})\" class='spanButton'>加入待归档</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已撤销
     * @return bool|string
     */
    public function revokeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            'workFlow' => '已撤销',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'revokeTime');
        }
        if (!$this->power('officialRevoke','seeAll')){
            $and .= self::seeSelf('officialRevoke');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'revokeTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("revokeForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='revokeForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 加入待归档
     */
    public function addArchive(): bool|string
    {
        $formName = $this->post('formName');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否将所选的公文加入待归档？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "加入待归档", "height" => 155, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 加入待归档
     */
    public function addArchiveEdit(): bool|string
    {
        $idArr = $this->post('listId')?:$this->post('issuedId');
        if (!$this->power('officialIssued', "archive") && !$this->power('officialRevoke', "archive") && !$this->power('officialAbolished', "archive")) {
            $json['warn'] = "你没有" . self::title . "的加入待归档权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        }else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['isArchive'] != '待归档'){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，不是待归档状态<br>";
                }elseif($info['state'] != '已通过'){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，还未审核通过<br>";
                }elseif(static::total(array('table'=>'archive',"where"=>"targetId = '$info[id]'")) >0){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，此公文已加入待归档<br>";
                }else{
                    $warn = static::insert(array(
                        'table'=>'archive',
                        'field'=>[
                            'id'=>self::getId(),
                            'type'=>'公文发文',
                            'targetId'=>$id,
                            'orderNo'=>$info['preText'],
                            'name'=>$info['title'],
                            'pageNum'=>$info['pageNum'],
                            'partNum'=>$info['partNum'],
                            'level'=>$info['secretLevel'],
                            'transferStid'=>self::$stid,
                            'transferDate'=>$this->date,
                            'transferDept'=>self::findStaffDepartment(self::$stid,'id'),
                            'workFlow'=>'待归档',
                            'fileDate'=>$info['issueDate'],
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功将{$x}个公文加入了待归档，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


    /*列表页-查询条件*/
    public function abolishedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已废止');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已废止
     *
     */
    public function abolished(): bool|string
    {
        $html = $this->abolishedOptions(false);
        //控件
        $button = "";
        if ($this->power('officialAbolished', "archive")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','addArchive',{formName:'abolishedForm'})\" class='spanButton'>加入待归档</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已废止
     * @return bool|string
     */
    public function abolishedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            'workFlow' => '已废止',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );
        $and = '';
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'abandTime');
        }
        if (!$this->power('officialAbolished','seeAll')){
            $and .= self::seeSelf('officialAbolished');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'abandTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("abolishedForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function documentAuditOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('审核中');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 审核中
     *
     */
    public function documentAudit(): bool|string
    {
        $html = $this->documentAuditOptions(false);
        //控件
        $button = "";
        if ($this->power('officialDocumentAudit', "issued")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{})\" class='spanButton'>签发</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function documentAuditSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            'workFlow' => '审核中',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'commitTime');
        }
        if (!$this->power('officialDocumentAudit','seeAll')){
            $and .= self::seeSelf('officialDocumentAudit');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'commitTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("auditForm", "auditId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "auditId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "approverId":
                        $audit = query('audit', "targetId = '$array[id]'");
                        $row[] = self::findStaff(explode(',', $audit['approverId']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='auditForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 批量签发
     */
    public function stateSwitch(): bool|string
    {
        $formName = 'auditForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认签发所选的公文？",
            ),
            array(
                must . "签发时间：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
        )));
        //返回
        return $this->layer(array("title" => "签发", "height" => 210, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 批量签发
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('auditId');
        if (!$this->power('officialDocumentAudit', "issued")) {
            $json['warn'] = "你没有" . self::title . "的签发权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择签发时间';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['state'] == '已通过' && $info['workFlow'] == '审核中') {
                    $warn = update(array('table' => self::table, 'field' => ['workFlow' => '已签发', 'signTime' => $this->post('signTime'), 'signStid' => self::$stid], 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //发送待办
                        $this->sendTip($info['member'],$info['id'],"您有一份公文【{$info['title']}】待签收");
                        $text .= $this->control['name'] . "签发了公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "签发了公文【{$info['title']}】， id：{$id} 失败，更新失败<br>";
                    }
                } else {
                    $text .= $this->control['name'] . "签发了公文【{$info['title']}】， id：{$id} 失败：还未审核通过或已签发<br>";
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => 'officialDocumentAudit', "text" => $text]);
            }
            $_SESSION['warn'] = "成功签发了{$x}个公文，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 发送待办
     */
    public function sendTip($staffId, string $id, string $text)
    {
        $id_list = explode(',', $staffId);
        if (is_array($id_list)) {
            $info = query(self::table,"id = '$id'");

            foreach ($id_list as $stid) {
                $reId = suiji();
                backlogIn([
                    "stid" => $stid,
                    "type" => '公文签收',
                    "typeId" => $reId,
                    "text" => $text,
                    'targetCla' => 'officialDocumentGet',
                    'targetFun' => 'detail'
                ]);
                $field = [
                    'id' => $reId,
                    'state' => '草稿',
                    'workFlow' => '待签收',
                    'classify' => '收文',
                    'prefixYear' => $info['prefixYear'],
                    'stid' => $stid,
                    'type' => $info['type'],
                    'title' =>$info['title'],
                    'summary' => $info['summary'],
                    'secretLevel' =>$info['secretLevel'],
                    'secretTime' => $info['secretTime'],
                    'issueDate' => $info['issueDate'],
                    'urgentLevel' => $info['urgentLevel'],
                    'pageNum' => $info['pageNum'],
                    'partNum' => $info['partNum'],
                    'list' => $info['list'],
                    'issueUnit' => $info['issueUnit'],
                    'prefix' => $info['prefix'],
                    'department' => $info['department'],
                    'copyDept' => $info['copyDept'],
                    'issuedDept' => $info['issuedDept'],
                    'content' => $info['content'],
                    'tag' => $info['tag'],
                    'selector' => $info['selector'],//员工选择器
                    'copyId'=>$info['id']
                ];
                $field['preText'] = $info['prefix'] . " [" . date('Y') . "] {$info['list']}号";
                static::insert(array(
                    'table'=>self::table,
                    'field'=>$field
                ));
            }
        }
    }

    /*列表页-查询条件*/
    public function issuedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已签发');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已签发
     */
    public function issued(): bool|string
    {
        $html = $this->issuedOptions(false);
        //控件
        $button = "";
        if ($this->power('officialIssued', "cancel")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','cancel',{})\" class='spanButton'>撤销</span>\n";
        }
        if ($this->power('officialIssued', "abandoned")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','abandoned',{})\" class='spanButton'>废止</span>\n";
        }
        if ($this->power('officialIssued', "archive")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','addArchive',{formName:'issuedForm'})\" class='spanButton'>加入待归档</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function issuedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            'workFlow' => '已签发',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'signTime');
        }
        if (!$this->power('officialIssued','seeAll')){
            $and .= self::seeSelf('officialIssued');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("issuedForm", "issuedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "issuedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "signStid":
                        $row[] = self::findStaff($array['signStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='issuedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 批量废止
     */
    public function abandoned(): bool|string
    {
        $formName = 'issuedForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "废止时间：" => text(array('name' => 'abandTime', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                must . '废止事由：' => textarea(array('name' => 'abandText', 'class' => 'textarea'))
            )
        )));
        //返回
        return $this->layer(array("title" => "废止", "height" => 280, "width" => 800, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 批量废止
     */
    public function abandonedEdit(): bool|string
    {
        $idArr = $this->post('issuedId');
        $field = array(
            'abandTime' => $this->post('abandTime'),
            'abandText' => $this->post('abandText'),
            'workFlow' => '已废止',
            'abandStid' => self::$stid
        );
        $annotation = [
            'abandTime' => '废止时间',
            'abandText' => '废止事由',
        ];
        $rules = [
            'abandTime' => 'required',
            'abandText' => 'required',
        ];
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if (!$this->power('officialIssued', "abandoned")) {
            $json['warn'] = "你没有" . self::title . "的废止权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['workFlow'] == '已签发') {
                    $warn = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        delete([
                            'table' => 'backlog',
                            'where' =>" workFlow = '待处理' and typeId in (select id from official_document where copyId = '$info[copyId]')",
                        ]);
                        $text .= $this->control['name'] . "废止了公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "废止了公文【{$info['title']}】， id：{$id} 失败，更新失败<br>";
                    }
                } else {
                    $text .= $this->control['name'] . "废止了公文【{$info['title']}】， id：{$id} 失败：不是已签发状态<br>";
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => 'officialIssued', "text" => $text]);
            }
            $_SESSION['warn'] = "成功废止了{$x}个公文，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 批量撤销
     */
    public function cancel(): bool|string
    {
        $formName = 'issuedForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "撤销时间：" => text(array('name' => 'revokeTime', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                must . '撤销事由：' => textarea(array('name' => 'revokeText', 'class' => 'textarea'))
            )
        )));
        //返回
        return $this->layer(array("title" => "撤销", "height" => 280, "width" => 800, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 撤销
     */
    public function cancelEdit(): bool|string
    {
        $idArr = $this->post('issuedId');
        $field = array(
            'revokeTime' => $this->post('revokeTime'),
            'revokeText' => $this->post('revokeText'),
            'workFlow' => '已撤销',
            'revokeStid' => self::$stid
        );
        $annotation = [
            'revokeTime' => '撤销时间',
            'revokeText' => '撤销事由',
        ];
        $rules = [
            'revokeTime' => 'required',
            'revokeText' => 'required',
        ];
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if (!$this->power('officialIssued', "cancel")) {
            $json['warn'] = "你没有" . self::title . "的撤销权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['workFlow'] == '已签发') {
                    $warn = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        delete([
                            'table' => 'backlog',
                            'where' =>" workFlow = '待处理' and typeId in (select id from official_document where copyId = '$info[copyId]')",
                        ]);
                        $text .= $this->control['name'] . "撤销了公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "撤销了公文【{$info['title']}】， id：{$id} 失败，更新失败<br>";
                    }
                } else {
                    $text .= $this->control['name'] . "撤销了公文【{$info['title']}】， id：{$id} 失败：不是已签发状态<br>";
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => 'officialIssued', "text" => $text]);
            }
            $_SESSION['warn'] = "成功撤销了{$x}个公文，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function allOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('全部');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 全部
     */
    public function all(): bool|string
    {
        $html = $this->allOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function allSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'发文',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
            "workFlow" => $this->post('workFlow'),
            "isArchive" => $this->post('isArchive'),
        );
        $and='';
        if (!$this->power(self::page,'seeAll')){
            $and .= self::seeSelf(self::page);
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='issuedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     *选择模板
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        $html =
            select(array("name" => "type", "title" => "公文种类", 'option' => explode("，", para("officialDocumentType")))) .
            text(array("name" => "templateName", "title" => "模板名称"));
        $button = "<input style='margin-left: 5px' onclick=\"chooseTemplate()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "选择模板", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        $like = [
            'name' => $this->post('templateName'),
        ];
        $equal = [
            'state' => '启用',
            'type' => $this->post('type'),
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "official_document_template",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $tr[] = ['', '公文种类', '模板名称'];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio'>",
                $array['type'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $templateId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($templateId)) {
            $json['warn'] = '请选择模板';
        } else {
            $template = query('official_document_template', "id = '$templateId'");
            $json['data'] = $template;
            $json['data']['tag'] = componentClass::singleInput(array('list' => explode(',', $template['tag'])));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "从模板新建",
            "type" => "点击事件",
            "title" => "从模板新建",
            'fun' => "layer('" . self::page . "','addMaterial',{})",
        ];

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body           = $this->edit4([
            '基本信息' => [
                [
                    must . "公文种类：" => select(["name" => "type", 'title' => '请选择', 'option' => explode('，', para('officialDocumentType')), "value" => $info['type']]),
                    must . "标题：" => text(["name" => "title", 'class' => 'text', "value" => $info['title']]),

                ],
                [
                    "摘要：" => textarea(["name" => "summary", 'class' => 'textarea', "value" => $info['summary']])
                ],
                [
                    "保密期限：" => text(["name" => "secretTime", 'class' => 'text', "value" => $info['secretTime']]),
                    "页数：" => text(["name" => "pageNum", "value" => $info['pageNum']]),
                    must . "密级：" => radio(["name" => "secretLevel", 'value' => explode('，',para('secretLevelOption')), "checked" => $info['secretLevel'] ?: '内部']),
                ],
                [
                    "份数：" => text(["name" => "partNum", "value" => $info['partNum']]),
                    "是否用印：" => radio(["name" => "isSeal", 'value' => ['是', '否'], "checked" => $info['isSeal'] ?: '否']),
                    must . "紧急程度：" => radio(["name" => "urgentLevel", 'value' => $this->urgentLevelOption, "checked" => $info['urgentLevel'] ?: '平急']),
                ],
                [
                    must . "发文单位：" => text(["name" => "issueUnit", 'class' => 'text', "value" => $info['issueUnit']]),
                    must ."发文日期：" => text(["name" => "issueDate", 'laydate' => [], "value" => $info['issueDate']]),
                    "发文字号：" => select(array('name' => 'prefix', 'title' => '请选择', 'option' => explode('，', para('officialDocumentPrefix')), 'value' => $info['prefix'])) . '[' . date('Y') . '] ' . text(array('name' => 'list', 'class' => 'textPrice', 'value' => $info['list'])) . '号',
                ],
                [
                    must . "主送单位：" => text(["name" => "department", 'class' => 'text', "value" => $info['department']]),
                    must . "主送人：" => selectMultiple(array('name'=>'member','sqlId'=>'stid','sqlField'=>'name','table'=>'staff','where'=>"state !='离职'",'title'=>'主送人','value'=>$info['member'])),
                    "抄送单位：" => text(["name" => "copyDept", 'class' => 'text', "value" => $info['copyDept']]),
                    "印发单位：" => text(["name" => "issuedDept", 'class' => 'text', "value" => $info['issuedDept']]),
                ],
                [
                    "主题词：" => "<div id='mainTag' class='full'>" . componentClass::singleInput(array('list' => explode(',', $info['tag']))) . "</div>",
                ],
                [
                    must . "正文：" => textarea(["name" => "content", 'class' => 'textarea', "value" => $info['content']]),
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'], '公文发文', self::page, self::page . 'EditForm'),
                ],
            ]
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    public function editJs(): string
    {
        return <<<eof
<script>
function chooseTemplate(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
         if (res.warn ==2){
             $("#officialDocumentSendAddMaterial").hide();
            $(".edit4 [name='type']").val(res.data.type);
            $(".edit4 [name='title']").val(res.data.title);
            $(".edit4 [name='issueUnit']").val(res.data.issueUnit);
            $(".edit4 [name='prefix']").val(res.data.prefix);
            $(".edit4 [name='department']").val(res.data.department);
            $(".edit4 [name='copyDept']").val(res.data.copyDept);
            $(".edit4 [name='issuedDept']").val(res.data.issuedDept);
            $(".edit4 [name='content']").val(res.data.content);
            $("#mainTag").html(res.data.tag);
         }else{
             msg(res.warn);
         }
    },'json');
}
</script>
eof;

    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $label_name = $this->post('label_name') ?: [];
        $field = [
            'type' => $this->post('type'),
            'title' => $this->post('title'),
            'summary' => $this->post('summary'),
            'secretLevel' => $this->post('secretLevel'),
            'secretTime' => $this->post('secretTime'),
            'issueDate' => $this->post('issueDate'),
            'urgentLevel' => $this->post('urgentLevel'),
            'pageNum' => $this->post('pageNum'),
            'partNum' => $this->post('partNum'),
            'list' => $this->post('list'),
            'issueUnit' => $this->post('issueUnit'),
            'prefix' => $this->post('prefix'),
            'department' => $this->post('department'),
            'copyDept' => $this->post('copyDept'),
            'issuedDept' => $this->post('issuedDept'),
            'member' => $this->post('member'),
            'content' => $this->post('content'),
            'tag' => implode(',', $label_name),
        ];

        $annotation = [
            'type' => '公文种类',
            'title' => '标题',
            'issueDate' => '发文日期',
            'secretLevel' => '密级',
            'urgentLevel' => '紧急程度',
            'issueUnit' => '发文单位',
            'department' => '主送单位',
            'member' => '主送人',
            'content' => '正文',
        ];
        $rules = [
            'type' => 'required',
            'title' => 'required',
            'issueDate' => 'required',
            'secretLevel' => 'required',
            'urgentLevel' => 'required',
            'issueUnit' => 'required',
            'member' => 'required',
            'department' => 'required',
            'content' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        $prefixYear =$info['id']?$info['prefixYear']:date('Y');
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "title = '$field[title]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此标题的公文';
        }elseif(!empty($field['prefix']) && empty($field['list'])){
            $json['warn'] = '请完整填写发文字号';
        }elseif (!empty($field['prefix']) && static::total(array('table' => self::table, 'where' => "prefix = '$field[prefix]' and prefixYear = '$prefixYear' and list = '$field[list]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此发文字号的公文';
        } else {
            if (!$info['id']) {
                $field['preText'] = $field['prefix']?$field['prefix'] . " [" . date('Y') . "] {$field['list']}号":'';
                $field = array_merge($field, [
                    'id' => $id,
                    'state' => '草稿',
                    'workFlow' => '草拟中',
                    'classify' => '发文',
                    'prefixYear' => date('Y'),
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $field['preText'] = $field['prefix'] . " [{$info['prefixYear']}] {$field['list']}号";
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交审批后触发
     * @param $data
     */
    public function commitAfter($data)
    {
        update(array('table' => self::table, 'field' => ['workFlow' => '审核中', 'commitTime' => $this->time], 'where' => "id = '$data[id]'"));
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '公文发文',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'commitAfter',
                                'data' => ['id' => $info['id']]
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state', 'workFlow'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                            'workFlow' => ['草拟中', '审核中'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state', 'workFlow'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                            'workFlow' => ['草拟中']
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            //按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];
                //按钮
                $button[] = [
                    "name" => "预览",
                    "type" => "点击事件",
                    "title" => "预览",
                    'fun' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&method=preview&table=".self::table."&id={$info['id']}')"
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $audit = query('audit', " targetId = '$info[id]'");
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "公文种类" => $info['type'],
                        "标题" => $info['title'],
                    ),
                    array(
                        "摘要" => pre($info['summary']),
                    ),
                    array(
                        "保密期限" => $info['secretTime'],
                        "页数" => $info['pageNum'],
                        "密级" => $info['secretLevel'],
                        "份数" => $info['partNum'],
                    ),
                    array(
                        "是否用印" => $info['isSeal'],
                        "紧急程度" => $info['urgentLevel'],
                        "发文单位" => $info['issueUnit'],
                        "发文日期" => $info['issueDate'],
                    ),
                    array(
                        "发文字号" => $info['preText'],
                        "主送单位" => $info['department'],
                        "抄送单位" => $info['copyDept'],
                        "印发单位" => $info['issuedDept'],
                    ),
                    array(
                        "主送人" =>self::findStaff($info['member'])
                    ),
                    array(
                        "摘要" => pre($info['content']),
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '公文发文')
                    )
                ),
                "系统信息" => array(
                    array(
                        "拟制人" => self::findStaff($info['stid']),
                        "拟制时间" => $info['time'],
                        "提交审批时间" => self::null($audit['commitTime']),
                        "签发时间" => self::null($info['passTime']),
                    ),
                    array(
                        "撤销时间" => self::null($info['abandTime']),
                        '撤销事由' => $info['abandText'],
                        "废止时间" => self::null($info['revokeTime']),
                        '废止事由' => $info['revokeText'],
                    ),
                    array(

                        "状态" => $info['workFlow'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' and classify = '发文' ");
                if ($info['state'] != '草稿') {
                    //返回
                    $warn = "删除失败：不是草稿状态";
                } else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


}
